package com.tiantianyuegou.activity;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tiantianyuegou.R;
import com.tiantianyuegou.app.SysApplication;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.util.MultipartEntity;
import com.tiantianyuegou.util.PictureUtil;
import com.tiantianyuegou.util.Tools;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;


/**
 * 个人资料
 */
public class MemberDataActivity extends BaseActivity implements View.OnClickListener {

    Dialog dialog;
    private RelativeLayout relative_head;
    private TextView text_account, text_data_idcard, data_mail, data_recommend, text_title, text_menu;
    private Button btn_exit;
    private ImageView portrait, img_title;
    private String TAG = "MemberDataActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_member_data);

        findViewByIds();


        Tools.changeSystemBar(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
        initListener();
    }

    public void findViewByIds() {

        img_title = (ImageView) findViewById(R.id.img_title);
        text_title = (TextView) findViewById(R.id.text_title);
        text_menu = (TextView) findViewById(R.id.text_menu);

        text_title.setText(R.string.member_data_title);

        relative_head = (RelativeLayout) findViewById(R.id.relative_head);

        text_account = (TextView) findViewById(R.id.text_account);
//        text_data_idcard = (TextView) findViewById(R.id.text_data_idcard);
//        data_mail = (TextView) findViewById(R.id.data_mail);
        data_recommend = (TextView) findViewById(R.id.data_recommend);

        portrait = (ImageView) findViewById(R.id.portrait);

        btn_exit = (Button) findViewById(R.id.btn_exit);

    }
    public void initData() {
        Intent intent = getIntent();
        text_account.setText(intent.getStringExtra("tmName"));
//        text_data_idcard.setText(intent.getStringExtra("tmIdcard"));
//        data_mail.setText(intent.getStringExtra("tmEmail"));
        data_recommend.setText("");
        ImageLoader.getInstance().displayImage(intent.getStringExtra("tmAvatar"), portrait);
    }


    public void initListener() {

        img_title.setOnClickListener(this);
        relative_head.setOnClickListener(this);
        btn_exit.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.img_title:
                finish();
                break;

            case R.id.relative_head:
                headDialog();
                break;

            case R.id.btn_exit:
                SysApplication.getInstance().exit();
                SPHelper.setTmId("");
                Intent intent=new Intent(MemberDataActivity.this,LoginActivity.class);
                intent.putExtra("type","exit");
                startActivity(intent);
                finish();

//                new YiLaGuanApp().addActivity(MemberDataActivity.this);
//                new YiLaGuanApp().exit();
                break;

            default:
                break;
        }
    }


    private void loadHead() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("tmId", SPHelper.getTmId() + "");
        params.addBodyParameter("file", System.currentTimeMillis() + ".jpg");
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.UPDATE_AVATAR, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e(TAG, "onSuccess response.result  " + responseInfo.result);
                String response = responseInfo.result;
                try {
                    JSONObject object = new JSONObject(response);
                    showMsg(object.getString("message"));

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });

    }

    private Uri imageFilePath;
    private final int MEDIA_CAMERA_REQUEST_CODE = 20394;
    private final int MEDIA_IMAGE_REQUEST_CODE = 20395;
    private final int MEDIA_CROP_REQUEST_CODE = 20396;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            Intent intent = new Intent("com.android.camera.action.CROP");
            Uri data2 = null;
            if (data == null) {
                data2 = PictureUtil.getImageUri();
            } else {
                data2 = data.getData();
            }

            if (requestCode == MEDIA_CROP_REQUEST_CODE) {
                Bitmap bitmap = decodeUriAsBitmap(imageFilePath);// decode
                // bitmap
                if (bitmap != null) {
                    portrait.setImageBitmap(bitmap);
                } else {
                    portrait.setImageBitmap(BitmapFactory.decodeResource(
                            getResources(), R.mipmap.ic_launcher));
                }

                portrait.setImageBitmap(bitmap);
                // byte[] b = Bitmap2Bytes(bitmap);
                uploadBmp(bitmap);
                // getQiniuToken(b); //上传头像到服务器端

            } else if (requestCode == MEDIA_IMAGE_REQUEST_CODE) {
                if (data != null) {
                    imageFilePath = data.getData();
                    cropImageUri(imageFilePath, 100, 100,
                            MEDIA_CROP_REQUEST_CODE);
                }
            } else if (requestCode == MEDIA_CAMERA_REQUEST_CODE) {
                cropImageUri(imageFilePath, 100, 100, MEDIA_CROP_REQUEST_CODE);
            } else if (requestCode == PictureUtil.PHOTO_PICKED_WITH_DATA) {
                intent.setDataAndType(data2, "image/*");
                intent.putExtra("crop", true);
                // 设置裁剪尺寸
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
                intent.putExtra("outputX", 130);
                intent.putExtra("outputY", 130);
                intent.putExtra("return-data", true);
                intent.putExtra(MediaStore.EXTRA_OUTPUT,
                        PictureUtil.getImageCaiUri());
                startActivityForResult(intent, PictureUtil.PHOTO_CROP);
            } else if (requestCode == PictureUtil.PHOTO_CROP) {
                Bundle bundle = data.getExtras();
                Bitmap myBitmap = (Bitmap) bundle.get("data");
                Bitmap bitImage = PictureUtil.comp(myBitmap);

                String fileName = PictureUtil.getCharacterAndNumber();
                File file = new File(PictureUtil.PHOTO_DIR, fileName + ".png");
               PictureUtil.saveMyBitmap(bitImage, file);

                portrait.setImageBitmap(bitImage);

//                 byte[] b = Bitmap2Bytes(bitImage);

                uploadBmp(bitImage);
//                getQiniuToken(b); //上传头像到服务器端
            }
        }


    }

    private void headDialog() {
        View view = getLayoutInflater().inflate(R.layout.dialog_head, null);
        dialog = new Dialog(this, R.style.transprentFrameWindowStyle);
        dialog.setContentView(view, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(true);

        Button dialog_photograph, dialog_photo, dialog_quit;

        dialog_photograph = (Button) view.findViewById(R.id.dialog_photograph);
        dialog_photo = (Button) view.findViewById(R.id.dialog_photo);
        dialog_quit = (Button) view.findViewById(R.id.dialog_quit);

        /**
         * 系统相机
         */
        dialog_photograph.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // 调用系统相机
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                ContentValues values = new ContentValues(3);
                values.put(MediaStore.Images.Media.DISPLAY_NAME, "testing");
                values.put(MediaStore.Images.Media.DESCRIPTION,
                        "this is description");
                values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                imageFilePath = MemberDataActivity.this.getContentResolver()
                        .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                values);

                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageFilePath);
                startActivityForResult(intent, MEDIA_CAMERA_REQUEST_CODE);
                dialog.dismiss();

            }
        });

        /**
         * 系统相册
         */
        dialog_photo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // 调用系统相册
               PictureUtil.doPickPhotoFromGallery(MemberDataActivity.this);
                dialog.dismiss();
            }
        });

        dialog_quit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.show();
    }


    /**
     * 上传图片目录到服务器
     */
    private void uploadBmp(Bitmap b) {
        new UploadTask().execute(b);
    }

    private class UploadTask extends AsyncTask<Bitmap, String, String> {
        ProgressDialog progressDialog = null;

        public UploadTask() {
            progressDialog = new ProgressDialog(MemberDataActivity.this);
            progressDialog.setTitle("请稍等");

            progressDialog.setMessage("正在请求数据");
            progressDialog.show();
        }

        protected String doInBackground(Bitmap... bitmaps) {
            if (bitmaps[0] == null)
                return null;

            Bitmap bitmap = bitmaps[0];
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            InputStream in = new ByteArrayInputStream(stream.toByteArray());

            DefaultHttpClient httpclient = new DefaultHttpClient();
            ByteArrayOutputStream baos;
            try {
                HttpPost httppost = new HttpPost(ApiDefine.UPDATE_AVATAR); // server

                MultipartEntity reqEntity = new MultipartEntity();

                reqEntity.addPart("tmId", SPHelper.getTmId() + "");
                reqEntity.addPart("photo", System.currentTimeMillis() + ".png",
                        in);

                httppost.setEntity(reqEntity);
                Log.e(TAG, System.currentTimeMillis() + ".png");

                System.out.println("requestLineInfo>>"
                        + httppost.getRequestLine());
                HttpResponse response = null;
                baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[8192];
                try {
                    response = httpclient.execute(httppost);
                    if (response != null) {
                        StatusLine statusLine = response.getStatusLine();
                        System.out.println(statusLine.getStatusCode());
                        if (statusLine != null
                                && statusLine.getStatusCode() == HttpStatus.SC_OK) {
                            InputStream is = response.getEntity().getContent();
                            baos.reset();
                            for (int len = is.read(buffer); len != -1; len = is
                                    .read(buffer)) {
                                baos.write(buffer, 0, len);
                            }
                            System.out.println(baos.toString());
                        }
                    }

                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    if (response != null)
                        System.out.println("responseInfo>>"
                                + response.getStatusLine().toString());
                } finally {

                }
            } finally {

            }

            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return baos.toString();
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            progressDialog.dismiss();
            uploadAvaterResult(result);
        }
    }

    /**
     * 解析是否上传头像成功
     */
    private void uploadAvaterResult(String resultJson) {
        try {
            JSONObject bean = new JSONObject(resultJson);
            String code=bean.getString("code");
            if("100".equals(code)){
                ImageLoader.getInstance().displayImage(bean.getString("result"), portrait);
            }
            Toast.makeText(this, bean.getString("message"), Toast.LENGTH_SHORT).show();
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    /**
     * bitmap 转换成字节
     */
    public byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    /**
     * Uri转化成Bmp
     */
    private Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver()
                    .openInputStream(uri));
        } catch (Throwable e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    /**
     * 裁剪图片
     */
    private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, requestCode);
    }

//    public static String getLocalVersionName(Context context)
//            throws NameNotFoundException {
//        PackageManager packageManager = context.getPackageManager();
//        PackageInfo packageInfo = packageManager.getPackageInfo(
//                context.getPackageName(), 0);
//        return packageInfo.versionName;
//    }

}